package com.app.couponsharelife.ui.main.login

import android.content.Intent
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.NewBindPhoneBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.FinishActivityManager
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.ui.main.login.fragment.PasswordLoginFragment
import com.app.couponsharelife.utils.AppUtils
import kotlinx.android.synthetic.main.activity_newlogin.*
import kotlinx.android.synthetic.main.newloginactivity_bgrvitm.view.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit


/**
 *Created by xct on 2018/12/28
 *Description:新登录页面
 */
class NewLoginActivity :BaseActivity(),View.OnClickListener{
    private var userId=""
    private var userName=""
    private var unionId=""
    private var headPrice=""
    private var sex="1"
    private var city=""
    private var province=""
    private var isvisible=false
    private val handler=MyHandler(this)
    private var disposable: Disposable? = null
    private var mPagers = arrayListOf<Fragment>()
    private val imagbg= arrayListOf<Int>(R.drawable.login_bg1,R.drawable.login_bg2,R.drawable.login_bg3,R.drawable.login_bg4,R.drawable.login_bg5)
    override val viewLayoutId: Int
        get() = R.layout.activity_newlogin

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        mPagers.add(PasswordLoginFragment())
        mPagers.add(PasswordLoginFragment())
        newlogin_bgrv.layoutManager=LinearLayoutManager(this)
        newlogin_bgrv.adapter=MyAdapter()
        newlogin_bgrv.setTouch(false)
        newlogin_bgrv.setScrollSpeed(2)
        newlogin_wexinll.setOnClickListener(this)
        newlogin_phone.setOnClickListener(this)
        newlogin_userxyll.setOnClickListener(this)
        newlogin_userxyll.setOnClickListener(this)
        newlogin_llclose.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.newlogin_wexinll->{
            val wechat= ShareSDK.getPlatform(Wechat.NAME)
            wechat.removeAccount(true)
            //wechat.SSOSetting(true)
            wechat!!.platformActionListener=object : PlatformActionListener {
                override fun onComplete(p0: Platform, p1: Int, p2: HashMap<String, Any>) {
                    //Log.e("eeee","---->"+p0.db.userId+"---"+p0.db["unionid"]+"---"+p0.db.userName+"---"+p0.db.userIcon)
                    //wxLogin(p0.db.userId,p0.db["unionid"],p0.db.userName,p0.db.userIcon)
                    isvisible=false
                    userId=p0.db.userId?:""
                    unionId=p0.db["unionid"]?:""
                    userName=p0.db.userName?:""
                    headPrice=p0.db.userIcon?:""
                    sex=p0.db["sex"]?:""
                    city=p0.db["city"]?:""
                    province=p0.db["province"]?:""
                    val msg=Message()
                    msg.what=0
                    handler.sendMessage(msg)
                }

                override fun onCancel(p0: Platform?, p1: Int) {
                    isvisible=false
                }

                override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                    //showToastMsg("登录失败")
                    isvisible=false
                }
            }
            if (wechat.isAuthValid) {
                wechat.removeAccount(true)
                return
            }
            wechat.showUser(null)
            isvisible=true
            }
            R.id.newlogin_phone->{
                startActivity(Intent(this,PhoneLoginActivity::class.java))
            }
            R.id.newlogin_userxyll->{
                startActivity(Intent(this,UserKnowActivity::class.java))
            }
            R.id.newlogin_llclose->{
                finish()
            }
        }
    }

    private fun wxLogin(openId:String,unionId:String,nickName:String,headPrice:String){
        val map = HashMap<String, String>()
        map["openId"] = openId
        map["unionId"] = unionId
        map["nickName"] = nickName
        map["headPrice"] = headPrice
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        //mViewModel?.freshWxLogin(map,true)
        RetrofitWorker.retrofitWorker.wxLogin(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<NewBindPhoneBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<NewBindPhoneBean>) {
                        dismissProgressDialog()
                        if (it.code == 200 && it.data!= null) {
                            showToastMsg("登录成功")
                            AppUtils.setString(Contacts.USER_MOBILE, it.data!!.mobile!!)
                            AppUtils.setString(Contacts.USERID, it.data!!.id!!)
                            AppUtils.setString(Contacts.ADZONE_ID, it.data!!.relation_id?:"")
                            AppUtils.setString(Contacts.USER_GRADE_ID, it.data!!.sellerlevel.toString())
                            AppUtils.setString(Contacts.UNIONID, unionId)
                            AppUtils.setString(Contacts.INVITATION_CODE, it.data!!.requestcode?:"")
                            AppUtils.setString(Contacts.COMMISSION_RATIO, it.data!!.commissionRatio?:"")
                            FinishActivityManager.getInstance().finishAllActivity()
                            startActivity(Intent(this@NewLoginActivity, MainActivity::class.java))
                        } else {
                            showToastMsg("请求失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){
                                val intent=Intent(this@NewLoginActivity,UserIdentitySelect::class.java)
                                intent.putExtra("UserId",userId)
                                intent.putExtra("UserName",userName)
                                intent.putExtra("UnionId",unionId)
                                intent.putExtra("HeadPrice",headPrice)
                                intent.putExtra("Sex",sex)
                                intent.putExtra("City",city)
                                intent.putExtra("Province",province)
                                startActivity(intent)
                            }
                        }
                    }
                })
    }
    override fun onResume() {
        super.onResume()
        if (isvisible){
            showProgressDialog("请稍后...")
        }
        if (disposable == null)
            disposable = Observable.interval(0, 2, TimeUnit.SECONDS)//10s 倒计时
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ aLong -> if (aLong != 0L) dismissProgressDialog() }) { dismissProgressDialog() }
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
        disposable?.dispose()
        disposable=null
    }

    private class MyHandler(activity: NewLoginActivity) : Handler() {
        private val mActivity: WeakReference<NewLoginActivity> = WeakReference<NewLoginActivity>(activity)
        private var activity:NewLoginActivity?=null

        override fun handleMessage(msg: Message) {
            if (activity== null) {
               activity=mActivity.get()
            }
            when (msg.what) {
                0 -> {
                    activity!!.wxLogin(activity!!.userId,activity!!.unionId,activity!!.userName,activity!!.headPrice)
                }
                else -> {

                }
            }
        }
    }
    inner class MyAdapter:RecyclerView.Adapter<MyHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            val view=LayoutInflater.from(this@NewLoginActivity).inflate(R.layout.newloginactivity_bgrvitm,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return 200
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {
            Glide.with(holder.itemView).asBitmap()
                    .apply(RequestOptions().error(R.drawable.login_bg1))
                    .load(imagbg[position%5])
                    .into(holder.imageView!!)
        }
    }
    inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var imageView:ImageView?=null
        init {
            imageView=itemview.newloginfrag_bgrvitemimg
        }
    }
}